﻿$(function () {
    'use strict';
    layui.use(['element', 'notice', 'layer', 'tree', 'table', 'treeTable', 'numberInput', 'iziToast'], function () {
        var layer = layui.layer,
            element = layui.element,
            tree = layui.tree,
            table = layui.table,
            treeTable = layui.treeTable,
            numberInput = layui.numberInput,
            notice = Util.notice !== null && Util.notice() !== null
                ? Util.notice() : layui.notice,
            iziToast = layui.iziToast;
        var lodash = _,
            numInputIns = null;
        //获取数据字典树分组名： 与数据库分类对应，以此获取相对应模块加载
        var DicTreeGroups = [], TableInstances = [];
        var $datadicgroup = $("div#datadicgroups>input");
        $datadicgroup.each(function () {
            let datagrp = {
                grpkey: $(this).data("treegroup"),
                grpval: $(this).data("treegroupname")
            };
            DicTreeGroups.push(datagrp);
            let tableobj = {
                grpkey: $(this).data("treegroup"),
                grpval: null
            };
            TableInstances.push(tableobj);
        });
        element.on('collapse(datadictree)', function (data) {
            if (!data.show) return false;
            let $collapsepanel = data.title.parent();
            let treegrpId = $collapsepanel.data("treeid"),
                treegrptype = $collapsepanel.data("treegroup");
            let $treeContainer = $collapsepanel.find("div.layui-colla-content");
            if ($treeContainer.length === 0 || $treeContainer.html().length > 0) return false;
            let $loading = Util.loading(true, 0);
            httpapi.fetchGet('/api/system/getsystemdatadictree?grouptype=' + treegrptype).then(res => {
                if (!httpapi.checkResponse(res)) {
                    //输入信息校验错误
                    notice.error(res.message);
                    $loading.remove();
                }
                else {//Success
                    tree.render({
                        elem: $treeContainer,
                        id: "systemdatadictree_" + treegrpId,
                        onlyIconControl: true,
                        data: res.data,
                        click: function (obj) {
                            rightpanelactive.displayrightpanel(obj.data);
                        }
                        //edit: ['add', 'update', 'del']
                    });
                    $loading.remove();
                }
            }).catch(error => notice.error("对不起，出现未知错误，请您联系系统管理员！"));
        });

        var rightpanelactive = {
            //按点击功能分类菜单树按钮加载数据模块，
            //参数id,pid,grouptype,datatype与 api接口：/api/system/getsystemdatadictree?grouptype=
            //返回数据命名一致
            displayrightpanel: function (treenodedata) {
                if (typeof treenodedata === "undefined" || treenodedata.length === 0) {
                    notice.error("获取菜单数据失败");
                    return false;
                }
                let dataid = treenodedata.id,
                    datapid = treenodedata.pid,
                    datagrouptype = treenodedata.grouptype,
                    datatype = treenodedata.datatype;
                let rightformpanel = lodash.find(DicTreeGroups, function (o) { return o.grpkey === datagrouptype; });
                $("#rightpanel form").addClass("layui-hide");
                let $displaypanel = $("#" + rightformpanel.grpval);
                $displaypanel.removeClass("layui-hide");
                switch (rightformpanel.grpval) { //与后台 EntityEnumConfig.DataDicGroup一致
                    case "Oragnize": //组织机构
                        this.reloadOrganizeTreeTable(datagrouptype);
                        break;
                    case "ModuleButton": //数据字典预定义功能模块需要加载的按钮
                        this.reloadModuleButtonTable(dataid, datapid, datagrouptype, datatype);
                        break;
                    default:
                        return false;
                }
            },

            reloadModuleButtonTable: function (id, pid, grouptype, datatype) {
                if (moduletableconfig) {
                    moduletableconfig.url = "/api/system/getsystemdatadicbtns";
                    moduletableconfig.where = {
                        Id: id,
                        ParentId: pid,
                        GroupType: grouptype,
                        DataType: datatype
                    };
                    let tableobj = lodash.find(TableInstances, function (o) { return o.grpkey === grouptype; });
                    if (tableobj.grpval === null) //注意，从这个地方可以看出lodash find返回的是数据引用
                        tableobj.grpval = table.render(moduletableconfig);
                    else
                        tableobj.grpval.reload(moduletableconfig);
                }
            },

            reloadOrganizeTreeTable: function (grouptype) {
                if (organizetableconfig) {//config已经在对应页面配置完成
                    let tableobj = lodash.find(TableInstances, function (o) { return o.grpkey === grouptype; });
                    if (tableobj.grpval === null) //注意，从这个地方可以看出lodash find返回的是数据引用
                        tableobj.grpval = treeTable.render(organizetableconfig);
                    else
                        tableobj.grpval.reload(organizetableconfig);
                }
            }
        };

        //url: int Id of newsItemId
        //datas: object for api parameters 
        //callback: function
        var updateTableRow = function (url, datas, callback) {
            if (!lodash.isObject(datas) && !lodash.isEmpty(datas))
                return false;
            var index = layer.load(2, { time: 10 * 1000 });
            httpapi.fetchGet(url, datas).then(res => {
                layer.close(index);
                if (!httpapi.checkResponse(res)) {
                    //输入信息校验错误
                    notice.error(res.message);
                }
                else {//Success
                    if (lodash.isFunction(callback)) {
                        callback(res.message, res.data);
                    }
                }
            }).catch(error => consol.error(error));
        };
        //-----------------组织机构表 相关操作--------------（Start）
        // 监听单元格单击事件
        //TreeTable不同于layui.table，无法监听到tool(filter) event事件
        treeTable.on('cell(organizetreetable)', function (obj) {
            if (obj.field === 'displayorder') {
                var data = obj.data;
                layer.open({
                    type: 1
                    , title: '设置排序'
                    , content: document.getElementById("displayorderInputTpl").innerHTML
                    , resize: false
                    , success: function (layero, index) {
                        var options = {
                            step: 1,
                            min: 1,
                            max: 150
                        };
                        if (numInputIns === null)
                            numInputIns = numberInput.render(options);
                        else numInputIns.reload(options);

                        numInputIns.setInitNumber(data.displayorder);
                    }
                    , btn: ['确定']
                    , yes: function (index, layero) {
                        var newsetVal = numInputIns.getCurrentNumber();
                        if (Util.isNumber(newsetVal)) {
                            updateTableRow('/api/system/setorganizeorder', { organizeid: data.id, order: newsetVal }, function (msg, neworder) {
                                if (msg.length > 0)
                                    notice.success(msg);
                                obj.update({
                                    displayorder: neworder//res.data
                                });
                            });
                        } else {
                            notice.error("请输入正确数值");
                        }
                        layer.close(index);
                    }
                });
            }
        });

        //监听表格数据行按钮 (组织机构树表)
        let editurl = "/system/organizemanage/edit",
            editWidowConfig = {
                title: "编辑/修改",
                type: 2,
                content: "",
                anim: 3,
                width: 620,
                height: 480,
                end: function () {
                    let tableobj = lodash.find(TableInstances, function (o) { return o.grpkey === 1; /*获取组织机构table实例*/ });
                    if (tableobj.grpval === null) //注意，从这个地方可以看出lodash find返回的是数据引用
                        tableobj.grpval = treeTable.render(organizetableconfig);
                    else
                        tableobj.grpval.reload(organizetableconfig);
                }
            },
            currentSystemModuleId = $("#currentSystemModuleId").val();
        treeTable.on('tool(organizetreetable)', function (obj) {
            var data = obj.data,
                thisElem = this,
                buttonid = layui.$(thisElem).data("buttonid");
            if (data.pid === 0) {
                layer.tips('顶层数据不允许编辑！', thisElem, {
                    tips: 1
                });
                return false;
            }
            if (obj.event === 'Edit') {
                editWidowConfig.content = editurl + "?moduleid=" + currentSystemModuleId + "&buttonid=" + buttonid + "&organizeid=" + data.id;
                Util.OpenMainWindow(editWidowConfig);
            } else if (obj.event === 'Delete') {
                layer.confirm("确定要进行删除操作吗？", function (confirmIndex) {
                    layer.close(confirmIndex);
                    iziToast.loading("删除中，请稍候...");
                    let node = new Object(DeleteNodeModel);
                    node.EntityId = data.id;
                    node.ButtonId = buttonid;
                    node.ModuleId = currentSystemModuleId;
                    httpapi.fetchPost("/api/system/organizemanage/delete", node).then(res => {
                        iziToast.destroy();
                        if (!httpapi.checkResponse(res)) {
                            //输入信息校验错误
                            notice.error(res.message);
                        }
                        else {//Success
                            let tableobj = lodash.find(TableInstances, function (o) { return o.grpkey === 1; /*获取组织机构table实例*/ });
                            if (tableobj.grpval === null) //注意，从这个地方可以看出lodash find返回的是数据引用
                                tableobj.grpval = treeTable.render(organizetableconfig);
                            else
                                tableobj.grpval.reload(organizetableconfig);
                            notice.success(res.message);
                        }
                    }).catch(error => consol.error(error));
                });
            }
        });
        //监听顶部按钮栏
        var PageButtonEvent = {
            Add: function (buttonid) {
                editWidowConfig.content = editurl + "?moduleid=" + currentSystemModuleId + "&buttonid=" + buttonid;
                Util.OpenMainWindow(editWidowConfig);
                return false;
            }
        };
        $('.pagebuttongroup .layui-btn').on('click', function (e) {
            e.preventDefault();
            var type = $(this).data('type');
            var buttonid = $(this).data("buttonid");
            PageButtonEvent[type] ? PageButtonEvent[type].call(this, buttonid) : '';
        });
        //-----------------组织机构表 相关操作--------------（End）
    });
});